<!--原料入场检验表-->
<template>
  <div class="table-wrapper w-100">
    <div class="title rounded shadow-harsh pv-10">
      花椒科研表

      <div class="search">

        <el-popover
          placement="bottom"
          trigger="click">

          <div class="flex-row">
            <el-button size="mini" type="success" @click="handleAdd()">新增</el-button>
            <loader tableName="flower_chili_study" apiName="flowerChiliStudy"></loader>
            <exporter tableName="flower_chili_study"></exporter>
          </div>

          <i slot="reference" class="el-icon-more mr-10"></i>
        </el-popover>


        <el-input
          v-model="search"
          size="mini"
          placeholder="输入样品名称关键字搜索" />
      </div>

    </div>
    <div>

      <!--    通过字段进行 filter-->
      <el-table
        :fit="true"
        :v-loading="loading"
        height="250px"
        size="small"
        class="w-100 rounded shadow-harsh p-5"
        :data="tableData.filter(data => !search || data.demoname.toLowerCase().includes(search.toLowerCase())).slice((currentPage-1)*10,currentPage*10)">

        <el-table-column
          type="index"
          width="50">
        </el-table-column>

        <el-table-column
          :prop="item.prop"
          :label="item.label"
          sortable show-overflow-tooltip
          align="center"
          :width="item.type === 'datetime' ? 180 : 100"
          v-for="(item, index) in header"
          :key="index">

          <template scope="scope" v-if="item.type=== 'datetime'">
            <el-date-picker
              style="width: 80%;"
              v-if="scope.$index === editIndex"
              v-model="scope.row[item.prop]"
              type="date"
              size="small"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
            </el-date-picker>
            <span style="color: #4f7ff9" v-else>{{scope.row[item.prop]}}</span>
          </template>

          <template scope="scope" v-else-if="item.type=== 'fixed'">
            <span>{{scope.row[item.prop]}}</span>
          </template>

          <template scope="scope" v-else-if="item.type=== 'picture'">
            <el-upload
              v-if="scope.$index === editIndex"
              class="avatar-uploader"
              action="/api/utils/uploadImage"
              :show-file-list="false"
              :on-success="handleAvatarSuccess">
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <img v-else class="avatar" :src="scope.row[item.prop]" alt="图片">
          </template>

          <template scope="scope" v-else>
            <el-input v-if="scope.$index === editIndex" size="small"
                      v-model="scope.row[item.prop]" placeholder="请输入内容">
            </el-input>
            <span v-else>{{scope.row[item.prop]}}</span>
          </template>
        </el-table-column>

        <el-table-column width="160px" align="right" fixed="right">
          <template slot-scope="scope">
            <span v-if="scope.$index !== editIndex">
              <el-button
                size="mini"
                type="warning"
                @click="editIndex = scope.$index; imageUrl = ''">修改
              </el-button>

              <el-popconfirm
                @confirm="handleDelete(scope.$index, scope.row)"
                title="您确定要删除数据吗?">
                <el-button
                  slot="reference"
                  size="mini"
                  type="danger">删除
                </el-button>
              </el-popconfirm>

            </span>
            <span v-else>
            <el-button
              size="mini"
              type="success"
              @click="saveEdit(scope.$index, scope.row)">保存
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleCancel">取消
            </el-button>
            </span>


          </template>
        </el-table-column>
      </el-table>

      <el-pagination class="pagination"
                     @current-change="handleCurrentChange"
                     :current-page="currentPage"
                     :page-size="10"
                     :total="tableData.length"
                     layout="total, prev, pager, next, jumper">
      </el-pagination>



    </div>

  </div>
</template>

<script>
import loader from "./loader";
import exporter from "./exporter";

export default {
  name: "ingredient-check-table",
  components: {
    loader,
    exporter
  },

  mounted() {

    this.$api.getFlowerChiliStudy().then(res => {
      this.tableData = res.data['records']
      //   .sort((a, b) => {
      //   return a.demoname - b.demoname
      // })
      this.loading = false
    })
  },
  computed: {

  },
  methods: {
    getTableIndexByIndex(index) {
      // 通过表的row index来获取表格数据中的row index 在 list 中使用要 -1
      return index + (this.currentPage - 1) * 10 + 1
    },


    handleDelete(index, row) {
      console.log(index, row);
      this.$api.editFlowerChiliStudy('remove', row.id, row).then(res => {
        console.log(res)
        if (res['success']) {
          let n = this.getTableIndexByIndex(index)
          console.log(n, this.tableData[n-1])
          this.tableData.splice(n-1, 1)

          this.$message({
            message: '删除成功',
            type: 'success',
            duration: 2000
          });
        }
      })
    },
    handleCurrentChange: function(currentPage) {
      this.currentPage = currentPage;
    },

    saveEdit(index, row) {

      let method = row.id ? 'update' : 'save'
      row.maintainTime = row.maintainTime + ' 00:00:00'
      row.exteriorPicture = this.imageUrl
      let o = row

      console.log('保存', row.id, index, row, o)
      this.$api.editFlowerChiliStudy(method, row.id ? row.id : 0, o).then(res => {
        console.log(res)
        this.$message({
          message: '保存成功',
          type: 'success',
          duration: 2000
        });
        this.imageUrl = null
        this.$set(this.tableData, this.getTableIndexByIndex(index)-1, res.data.data)
        this.editIndex = null
      })

    },
    handleCancel: function() {
      this.editIndex = null
      this.tableData = this.tableData.filter(ele => {
        return ele.id
      })
    },
    handleAdd: function() {
      /*
      * 新增列按照 name * 来识别
      * */

      // 去除之前操作的痕迹
      this.imageUrl = ''
      this.tableData = this.tableData.filter(ele => {
        return ele.id
      })

      this.tableData.push({})
      let nums = this.tableData.length
      console.log(Math.floor((nums-1) / 10) + 1)
      this.currentPage = Math.floor((nums-1) / 10) + 1

      this.editIndex = nums % 10 === 0 ? 9 : nums % 10 - 1
    },

    handleAvatarSuccess(res, file) {
      console.log(res, file)
      this.imageUrl = res.data.fileInfo.imageUrl

    },

  },

  data() {
    return {
      tableData: [],
      search: "",
      currentPage: 1,
      loading: true,
      editIndex: null,


      imageUrl: null,
      visible: false,

      header: [
        {
          "prop": "createTime",
          "label": "插入时间",
          "type": "fixed"
        },
        {
          "prop": "updateTime",
          "label": "修改时间",
          "type": "fixed"
        },
        {
          "prop": "orderId",
          "label": "序号",
          "type": "String"
        },
        {
          "prop": "chineseName",
          "label": "中文名称",
          "type": "String"
        },
        {
          "prop": "commonName",
          "label": "通俗名称",
          "type": "String"
        },
        {
          "prop": "exteriorPicture",
          "label": "原料外观图",
          "type": "picture"
        },
        {
          "prop": "breed",
          "label": "品种",
          "type": "String"
        },
        {
          "prop": "origin",
          "label": "产地",
          "type": "String"
        },
        {
          "prop": "shapeParameter",
          "label": "外形参数",
          "type": "String"
        },
        {
          "prop": "seedContain",
          "label": "闭眼椒、椒籽含量",
          "type": "String"
        },
        {
          "prop": "fruitStemPercent",
          "label": "果梗质量占比",
          "type": "String"
        },
        {
          "prop": "plumPetalsPercent",
          "label": "梅花瓣质量占比",
          "type": "String"
        },
        {
          "prop": "leavesPercent",
          "label": "花椒叶质量占比",
          "type": "String"
        },
        {
          "prop": "flowerChiliElementContain",
          "label": "花椒麻素含量，g/kg",
          "type": "String"
        },
        {
          "prop": "nonVolatileEtherExtract",
          "label": "不挥发性乙醚提取物%",
          "type": "String"
        },
        {
          "prop": "moldSeedPercent",
          "label": "霉粒质量占比",
          "type": "String"
        },
        {
          "prop": "color",
          "label": "色泽",
          "type": "String"
        },
        {
          "prop": "colorParameter",
          "label": "色度参数",
          "type": "String"
        },
        {
          "prop": "flowerChiliSmellType",
          "label": "花椒香型",
          "type": "String"
        },
        {
          "prop": "shape",
          "label": "外观及均匀性",
          "type": "String"
        },
        {
          "prop": "totalAsh",
          "label": "总灰分",
          "type": "String"
        },
        {
          "prop": "waterPercent",
          "label": "水分",
          "type": "String"
        },
        {
          "prop": "maintainer",
          "label": "维护人",
          "type": "String"
        },
        {
          "prop": "maintainTime",
          "label": "维护时间",
          "type": "datetime"
        }
      ]
    };
  },
};
</script>

<style scoped>



.avatar-uploader .el-upload {
  border: 1px dashed #616161;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 10px;
  color: #8c939d;
  width: 40px;
  height: 40px;
  line-height: 40px;
  text-align: center;
}
.avatar {
  width: 40px;
  height: 40px;
}
</style>